﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;

namespace Smith.ImageConverter
{
    public class JPEGDConvert : BaseConvert, IConvert
    {
        static readonly short[] DefaultLuminanceTable = new short[64]
        {
            16, 11, 10, 16, 24, 40, 51, 61,
            12, 12, 14, 19, 26, 58, 60, 55,
            14, 13, 16, 24, 40, 57, 69, 56,
            14, 17, 22, 29, 51, 87, 80, 62,
            18, 22, 37, 56, 68, 109, 103, 77,
            24, 35, 55, 64, 81, 104, 113, 92,
            49, 64, 78, 87, 103, 121, 120, 101,
            72, 92, 95, 98, 112, 100, 103, 99
        };

        static readonly short[] DefaultChrominanceTable = new short[64]
        {
            17, 18, 24, 47, 99, 99, 99, 99,
            18, 21, 26, 66, 99, 99, 99, 99,
            24, 26, 56, 99, 99, 99, 99, 99,
            47, 66, 99, 99, 99, 99, 99, 99,
            99, 99, 99, 99, 99, 99, 99, 99,
            99, 99, 99, 99, 99, 99, 99, 99,
            99, 99, 99, 99, 99, 99, 99, 99,
            99, 99, 99, 99, 99, 99, 99, 99
        };

        public JPEGDConvert()
        {
            CodeInfo = GetImageCodeInfo("image/jpeg");
            Parameters = new EncoderParameters();
            Parameters.Param = new EncoderParameter[] { 
                new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L),
                new EncoderParameter(System.Drawing.Imaging.Encoder.LuminanceTable, DefaultLuminanceTable), 
                new EncoderParameter(System.Drawing.Imaging.Encoder.ChrominanceTable, DefaultChrominanceTable)};
        }

        public override void Save(Bitmap image, string path)
        {
            // draw a white background for png image
            if (image.Tag.Equals(ImageFormat.Png))
            {
                using (Bitmap img = new Bitmap(image.Width, image.Height))
                {
                    using (Graphics g = Graphics.FromImage(img))
                    {
                        g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height);
                        g.DrawImage(image, 0, 0, image.Width, image.Height);
                        //img.Save(path, ImageFormat.Jpeg);
                        image.Save(path, CodeInfo, Parameters);
                    }
                }
            }
            else
            {
                //image.Save(path, ImageFormat.Jpeg);
                image.Save(path, CodeInfo, Parameters);
            }
        }
    }
}
